package cn.itcast.bos.service.take_delivery.impl;

import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.take_delivery.WayBillRepository;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.index.WayBillIndexRepository;
import cn.itcast.bos.service.take_delivery.WayBillService;

@Service
@Transactional
public class WayBillServiceImpl implements WayBillService {

	@Autowired
	private WayBillRepository wayBillRepository;

	@Autowired
	private WayBillIndexRepository wayBillIndexRepository;

	@Override
	public void save(WayBill wayBill) {
		WayBill persistWayBill = wayBillRepository.findByWayBillNum(wayBill.getWayBillNum());
		// 判断运单号是否存在
		if (persistWayBill == null || persistWayBill.getId() ==null) {
			// 如果不存在则保存
			wayBill.setSignStatus(1);
			wayBillRepository.save(wayBill);

			// 保存索引
			wayBillIndexRepository.save(wayBill);
		} else {
			// 如果存在则修改
			try {
				//如果运单状态为带发货状态， 则允许修改， 否则订单将不能再被修改
				if(persistWayBill.getSignStatus()==1){
					Integer id = persistWayBill.getId();
					BeanUtils.copyProperties(persistWayBill, wayBill);
					persistWayBill.setId(id);
					persistWayBill.setSignStatus(1);
					// 保存索引
					wayBillIndexRepository.save(persistWayBill);
				}else{
					throw new RuntimeException("运单已发货，无法修改保存");
				}
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}

	}

	@Override
	public Page<WayBill> findPageData(WayBill wayBill, Pageable pageable) {
		// 判断查询条件是否存在
		if (StringUtils.isBlank(wayBill.getWayBillNum())
				&& StringUtils.isBlank(wayBill.getSendAddress())
				&& StringUtils.isBlank(wayBill.getRecAddress())
				&& StringUtils.isBlank(wayBill.getSendProNum())
				&& (wayBill.getSignStatus() == null || wayBill.getSignStatus() == 0)) {
			return wayBillRepository.findAll(pageable);
		} else {
			// BoolQueryBuilder布尔查询 可以组合多个查询条件
			System.out.println("条件查询=================================");
			BoolQueryBuilder query = new BoolQueryBuilder();
			// 当的运单号不为空
			if (StringUtils.isNoneBlank(wayBill.getWayBillNum())) {
				QueryBuilder tempBuilder = new TermQueryBuilder("wayBillNum",
						wayBill.getWayBillNum());
				System.out.println(
						"==================~~~======================" + tempBuilder.toString());
				query.must(tempBuilder); // 条件必须成立，相当于and
			}
			if (StringUtils.isNoneBlank(wayBill.getSendAddress())) {
				// 第一种情况 模糊查询
				QueryBuilder wildcardBuilder = new WildcardQueryBuilder("sendAddress",
						"*" + wayBill.getSendAddress() + "*");

				// 情况二： 输入"北京市天安门" 是多个词条组合，进行分词后 每个词条匹配查询
				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(
						wayBill.getSendAddress()).field("sendAddress")
								.defaultOperator(Operator.AND);
				// 两种情况 取or的关系
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardBuilder);
				boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder); // 条件必须成立，相当于and
			}
			if (StringUtils.isNoneBlank(wayBill.getRecAddress())) {
				QueryBuilder wildcardBuilder = new WildcardQueryBuilder("recAddress",
						"*" + wayBill.getRecAddress() + "*");
				query.must(wildcardBuilder); // 条件必须成立，相当于and
			}
			if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
				QueryBuilder tempBuilder = new TermQueryBuilder("sendProNum",
						wayBill.getSendProNum());
				query.must(tempBuilder); // 条件必须成立，相当于and
			}
			if (wayBill.getSignStatus() != null && wayBill.getSignStatus() != 0) {
				QueryBuilder tempBuilder = new TermQueryBuilder("signStatus",
						wayBill.getSignStatus());
				query.must(tempBuilder); // 条件必须成立，相当于and
			}

			SearchQuery searchQuery = new NativeSearchQuery(query);
			searchQuery.setPageable(pageable);// 分页效果

			return wayBillIndexRepository.search(searchQuery);
		}

	}

	@Override
	public WayBill findByWayBillNum(String wayBillNum) {

		return wayBillRepository.findByWayBillNum(wayBillNum);
	}
	
	@Override
	//定时Qurtz同步elasticsearch的数据
	public void syncIndex(){
		//查询数据  获取所有的WayBill
		List<WayBill> wayBills = wayBillRepository.findAll();
		
		wayBillIndexRepository.save(wayBills);
	}

	@Override
	public List<WayBill> findAll(WayBill wayBill) {
		// 判断查询条件是否存在
				if (StringUtils.isBlank(wayBill.getWayBillNum())
						&& StringUtils.isBlank(wayBill.getSendAddress())
						&& StringUtils.isBlank(wayBill.getRecAddress())
						&& StringUtils.isBlank(wayBill.getSendProNum())
						&& (wayBill.getSignStatus() == null || wayBill.getSignStatus() == 0)) {
					return wayBillRepository.findAll();
				} else {
					// BoolQueryBuilder布尔查询 可以组合多个查询条件
					System.out.println("条件查询=================================");
					BoolQueryBuilder query = new BoolQueryBuilder();
					// 当的运单号不为空
					if (StringUtils.isNoneBlank(wayBill.getWayBillNum())) {
						QueryBuilder tempBuilder = new TermQueryBuilder("wayBillNum",
								wayBill.getWayBillNum());
						System.out.println(
								"==================~~~======================" + tempBuilder.toString());
						query.must(tempBuilder); // 条件必须成立，相当于and
					}
					if (StringUtils.isNoneBlank(wayBill.getSendAddress())) {
						// 第一种情况 模糊查询
						QueryBuilder wildcardBuilder = new WildcardQueryBuilder("sendAddress",
								"*" + wayBill.getSendAddress() + "*");

						// 情况二： 输入"北京市天安门" 是多个词条组合，进行分词后 每个词条匹配查询
						QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(
								wayBill.getSendAddress()).field("sendAddress")
										.defaultOperator(Operator.AND);
						// 两种情况 取or的关系
						BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
						boolQueryBuilder.should(wildcardBuilder);
						boolQueryBuilder.should(queryStringQueryBuilder);

						query.must(boolQueryBuilder); // 条件必须成立，相当于and
					}
					if (StringUtils.isNoneBlank(wayBill.getRecAddress())) {
						QueryBuilder wildcardBuilder = new WildcardQueryBuilder("recAddress",
								"*" + wayBill.getRecAddress() + "*");
						query.must(wildcardBuilder); // 条件必须成立，相当于and
					}
					if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
						QueryBuilder tempBuilder = new TermQueryBuilder("sendProNum",
								wayBill.getSendProNum());
						query.must(tempBuilder); // 条件必须成立，相当于and
					}
					if (wayBill.getSignStatus() != null && wayBill.getSignStatus() != 0) {
						QueryBuilder tempBuilder = new TermQueryBuilder("signStatus",
								wayBill.getSignStatus());
						query.must(tempBuilder); // 条件必须成立，相当于and
					}

					SearchQuery searchQuery = new NativeSearchQuery(query);
					//elastisearch 允许查询的最大范围为10000
					Pageable pageable = new PageRequest(0, 10000);
					searchQuery.setPageable(pageable);// 分页效果

					return wayBillIndexRepository.search(searchQuery).getContent();
				}

	}

}
